package com.itheima.sfbx.trade.face.impl;

import com.itheima.sfbx.framework.commons.constant.trade.TradeCacheConstant;
import com.itheima.sfbx.framework.commons.dto.trade.TradeVO;
import com.itheima.sfbx.trade.adapter.WapPayAdapter;
import com.itheima.sfbx.trade.face.WapPayFace;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName WapPayFaceImpl.java
 * @Description 手机网页支付Face接口实现
 */
@Slf4j
@Component
public class WapPayFaceImpl implements WapPayFace {

    @Autowired
    WapPayAdapter wapPayAdapter;

    @Autowired
    RedissonClient redissonClient;

    @Override
    public TradeVO wapTrade(TradeVO tradeVO) {
        //对交易订单加锁
        Long productOrderNo = tradeVO.getProductOrderNo();
        String key = TradeCacheConstant.LOCK_PREFIX + productOrderNo;
        RLock lock = redissonClient.getLock(key);
        try {
            boolean b = lock.tryLock(TradeCacheConstant.REDIS_WAIT_TIME, TradeCacheConstant.REDIS_LEASETIME, TimeUnit.SECONDS);
            if(b){
                try {
                    return wapPayAdapter.wapTrade(tradeVO);
                } finally {
                    lock.unlock();
                }

            }else{
                throw new RuntimeException("你的操作太频繁了");
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
